#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import sys
import libdatadisks
from parted import _ped
from libdatadisks.util import Util


def usage():
    lineLength = 80

    print('Any USB stick, SD card, removable harddisk or other storage media can be your data disk.')
    print('')

    print('Usage:')
    print('  mkdatadisk DEVICE [--set-label LABEL] [--make-compatible-with OS,OS...] [--verbose]')
    print('')

    print('Description:')
    print('  To prepare a non-compliant storage medium for use with datadisks, use this command to format it as your data disk.')
    print('  Please note that this command may erase all data on the storage medium.')
    print('')

    print('The compatible OS list are as follows:')
    line = ""
    for member in libdatadisks.CompatibleOs:
        line2 = line + str(member) + ", "
        if len(line2) > lineLength:
            print(line)
            line = str(member) + ", "
        else:
            line = line2
    print('')


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        usage()
        sys.exit(1)

    if sys.argv[1] == "--help":
        usage()
        sys.exit(0)

    devPath = sys.argv[1]
    label = None
    compatibleOsList = None
    bVerbose = False

    i = 2
    while i < len(sys.argv):
        if sys.argv[i] == "--set-label":
            if label is not None:
                die("Duplicate --set-label specified.")
            if len(sys.argv) < i + 2:
                die("No LABEL specifiec for --set-label.")
            label = sys.argv[i + 1]
            # FIXME: check label length
            i += 2
            continue
        if sys.argv[i] == "--make-compatible-with":
            if compatibleOsList is not None:
                die("Duplicate --make-compatible-with specified.")
            if len(sys.argv) < i + 2:
                die("No OS specifiec for --make-compatible-with.")
            compatibleOsList = []
            for cos in sys.argv[i + 1].split(","):
                try:
                    compatibleOsList.append(libdatadisks.CompatibleOs(cos))
                except ValueError:
                    die("Invalid OS \"%s\" specified" % (cos))
            if len(compatibleOsList) == 0:
                die("Invalid OS \"%s\" specified" % (cos))
            i += 2
            continue
        if sys.argv[i] == "--verbose":
            if bVerbose:
                die("Duplicate --verbose specified.")
            bVerbose = True
            i += 1
            continue
        die("Redundant argument \"%s\" specified" % (sys.argv[i]))

    if label is None:
        label = ""
    if compatibleOsList is None:
        compatibleOsList = libdatadisks.CompatibleOs.get_default_compatible_os_list()

    obj = None
    try:
        obj = libdatadisks.create_data_disk(devPath, label, compatibleOsList)
    except libdatadisks.CreateError as e:
        die(e.message)
    except _ped.IOException as e:
        die(str(e))

    if bVerbose:
        print("Device: %s" % (obj.dev_path))

        if obj.label is not None:
            print("Label: %s" % (obj.label))

        print("PartitionTableType: %s" % (obj.partition_table_type))

        print("FileSystem: %s" % (obj.fs))

        print("FileSystem-UUID: %s" % (obj.fs_uuid))

        sz = Util.getBlkDevSize(obj.get_partition_dev_path())
        print("Size: %s" % (Util.formatSize(sz)))
